package com.csyf.manager.schedule;

import com.csyf.manager.entity.SysAccountBalance;
import com.csyf.manager.entity.SysAliAccount;
import com.csyf.manager.service.SysAccountBalanceBiz;
import com.csyf.manager.service.SysAliAccountBiz;
import com.csyf.manager.service.SysWithdrawalRecordService;
import com.csyf.manager.service.impl.RedisService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/**
 * @Author: Enzo
 * @Date: 2018/10/27 20:38
 */
public class AccountMoneyProcessSchedule implements Job {


    @Autowired
    private RedisService redisService;

    @Autowired
    private SysAliAccountBiz sysAliAccountBiz;

    @Autowired
    private SysAccountBalanceBiz sysAccountBalanceBiz;


    @Autowired
    private SysWithdrawalRecordService sysWithdrawalRecordService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        SysAliAccount sysAliAccount = new SysAliAccount();
        List<SysAliAccount> select = sysAliAccountBiz.select(sysAliAccount);

        for (SysAliAccount aliAccount : select) {


            Calendar instance = Calendar.getInstance();
            //前一天日期
            instance.add(Calendar.DATE, -1);
            String beforeonedate = new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime());
            String yyyyMMdd = new SimpleDateFormat("yyyyMMdd").format(instance.getTime());
            BigDecimal yesterdayMoney = sysAccountBalanceBiz.queryBalance(aliAccount.getAppid(),2);


            SysAccountBalance sysAccountBalance = new SysAccountBalance();
            sysAccountBalance.setMerchantno(aliAccount.getAppid());
            sysAccountBalance.setCurdate(beforeonedate);
            String srcmchkey_profit = "trade:srcmch_profit:" + yyyyMMdd + ":" + aliAccount.getAppid();
            String s = redisService.get(srcmchkey_profit);
            BigDecimal total = null != s ? new BigDecimal(s) : BigDecimal.ZERO;
            sysAccountBalance.setTotalprofit(total);

            BigDecimal bigDecimal = sysWithdrawalRecordService.queryTotalCase(aliAccount.getAppid(), beforeonedate);
            sysAccountBalance.setTotalcashout(bigDecimal);
            sysAccountBalance.setFrozen(BigDecimal.ZERO);


            sysAccountBalance.setTotalmoney(yesterdayMoney
                    .add(sysAccountBalance.getTotalprofit())
                    .subtract(sysAccountBalance.getTotalcashout())
                    .subtract(sysAccountBalance.getFrozen())
            );


            sysAccountBalanceBiz.insert(sysAccountBalance);

        }
    }
}
